var track_id='';
var watch_id=null;
var tracking_data = [];
$(#startTracking_start).live('click',function(){
	watch_id = navigator.geolocation.watchPosition(
		function(position)
		{
			tracking_data.push(position);
		},
		function(error)
		{
			console.log(error);
		},
		{frequency:3000, enableHighAccuracy: true});
	track_id = $("#track_id").val();
	$("#track_id").hide();
	$("#startTracking_status").html("Tracking workout: <strong>" + track_id + "</strong>");
});
$("#startTracking_stop").live('click',function(){
	navigator.geolocation.clearWatch(watch_id);
	window.localStorage.setItem("track_id",JSON.stringify(tracking_data));
	var watch_id = null;
	var tracking_data = [];
	$("#track_id").val("").show();
	$("#startTracking_status").html("Stopped tracking workout: <strong>" + track_id + "</strong>");
});
$("#home_clearstorage_button").live('click',function(){
	window.localStorage.clear();
});
$("#home_seedgps_button").live("click",function(){
	window.localStorage.setItem('Sample block', '[{"timestamp":1335700802000,"coords":{"heading":null,"altitude":null,"longitude":170.33488333333335,"accuracy":0,"latitude":-45.87475166666666,"speed":null,"altitudeAccuracy":null}},{"timestamp":1335700803000,"coords":{"heading":null,"altitude":null,"longitude":170.33481666666665,"accuracy":0,"latitude":-45.87465,"speed":null,"altitudeAccuracy":null}},{"timestamp":1335700804000,"coords":{"heading":null,"altitude":null,"longitude":170.33426999999998,"accuracy":0,"latitude":-45.873708333333326,"speed":null,"altitudeAccuracy":null}},{"timestamp":1335700805000,"coords":{"heading":null,"altitude":null,"longitude":170.33318333333335,"accuracy":0,"latitude":-45.87178333333333,"speed":null,"altitudeAccuracy":null}},{"timestamp":1335700806000,"coords":{"heading":null,"altitude":null,"longitude":170.33416166666666,"accuracy":0,"latitude":-45.871478333333336,"speed":null,"altitudeAccuracy":null}},{"timestamp":1335700807000,"coords":{"heading":null,"altitude":null,"longitude":170.33526833333332,"accuracy":0,"latitude":-45.873394999999995,"speed":null,"altitudeAccuracy":null}},{"timestamp":1335700808000,"coords":{"heading":null,"altitude":null,"longitude":170.33427333333336,"accuracy":0,"latitude":-45.873711666666665,"speed":null,"altitudeAccuracy":null}},{"timestamp":1335700809000,"coords":{"heading":null,"altitude":null,"longitude":170.33488333333335,"accuracy":0,"latitude":-45.87475166666666,"speed":null,"altitudeAccuracy":null}}]');
});
$("#history").live("pageshow",function(){
	tracks_recorded = window.localStorage.length;
	$("#tracks_recorded").html("<strong>" + tracks_recorded + "</strong> workout(s) recorded");
	$("#history_tracklist").empty();
	for(i=0;i<tracks_recorded;i++)
	{
		$("#history_tracklist").append("<li><a href='#track_info' data-ajax='false'>" + localStorage.key(i) + "</a></li>");
	}
	$("#history_tracklist").listview('refresh');
});
function gps_distance(lat1, lon1, lat2, lon2)
{
	var R=6371;
	var dLat = (lat2-lat1)*(Math.PI/180);
	var dLon = (lon2-lon1)*(Math.PI/180);
	var lat1=lat1*(Math.PI/180);
	var lat2=lat2*(Math.PI/180);
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;
    return d;
}

$("#history_tracklist li a").live('click',function(){
	$("#track_info").attr("track_id",$(this).text());
});
$("#track_info).live("pageshow",function(){
	var key = $(this).attr("track_id");
	$("#track_info div[data-role=header] h1").text(key);
	var data = window.localStorage.getItem(key);
	data = JSON.parse(data);
	
	//Calculate the distance
	total_km = 0;
	for (i=0; i<data.length; i++)
	{
		if (i==data.length-1) break;
		total_km += gps_distance(data[i].coords.latitude, data[i].coords.longitude, data[i+1].coords.latitude, data[i+1].coords.longitude);		
	}
	total_km_rounded = total_km.toFixed(2);
	
	//Calcutlate the duration
	start_time = new Date(data[0].timestamp).getTime();
	end_time = new Date(data[data.length-1].timestamp).getTime();
	total_time_ms = end_time - start_time;
	total_time_s = total_time_ms / 1000;
	final_time_m = Math.floor(total_time_s / 1000);
	final_time_s = total_time_s - (final_time_m * 60);
	//show infomation about the workout
	$("#track_info_info").html("Travelled <strong>" + total_km_rounded + "km</strong> in <strong>" + final_time_m + "m" + final_time_s + "s</strong>");
	
	//plot the route on Google map
	var myLatLng = new google.maps.LatLng(data[0].coords.latitude,data[0].coords.longtitude);
	var myOptions= {
		zoom:15,
		center:myLatLng,
		mapTypeId=google.maps.MapTypeId.ROADMAP;
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
	track_coords = [];
	for (i=0; i<data.length; i++){
		track_coords.push(new google.maps.LatLng(data[i].coords.latitude,data[i].coords.longtitude);
	}
	var trackPath = new google.maps.Polyline({
		path:track_coords,
		strokeColor:"#FF0000",
		strokeOpacity:1.0,
		strokeWeight:2
	});
	trackPath.setMap(map);
});
function onLoad()
{
	document.addEventListener("deviceready",function(){
		if (navigator.network.connection.type == Connection.NONE)
		{
			$("#home_network_button").text("No internet access")
									.attr("data-icon","delete")
									.button("refresh");
		}
	});
}







